<template>
	<div class="room-manage-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">{{ mode === 'edit' ? '编辑包间' : '创建包间' }}</h2>

				<el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="120px">
					<!-- 包间名称 -->
					<el-form-item label="包间名称" prop="roomName" required>
						<el-input v-model="form.roomName" placeholder="请输入包间名称" maxlength="50" show-word-limit />
					</el-form-item>

					<!-- 包间主图 -->
					<el-form-item label="包间主图（封面）" prop="image">
						<el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
							:on-change="handleMainImageChange" :http-request="uploadMainImage">
							<img v-if="form.image" :src="form.image" class="avatar" />
							<el-icon v-else class="avatar-uploader-icon">
								<Plus />
							</el-icon>
						</el-upload>
					</el-form-item>

					<!-- 包间图片 -->
					<el-form-item label="包间图片(最多上传5张)" prop="roomImages">
						<el-upload action="#" list-type="picture-card" :auto-upload="false" :on-preview="showPreview"
							:before-remove="handleRemoveImage" :limit="5" :http-request="customUpload"
							:on-change="handleFileChange"
							:file-list="form.roomImages.map(img => ({ url: img.imageUrl, id: img.id }))">
							<el-icon class="avatar-uploader-icon">
								<Plus />
							</el-icon>
						</el-upload>
						<div slot="tip" class="upload-footer">
							<el-button type="success" @click="submitUpload">
								上传至服务器
							</el-button>
						</div>
					</el-form-item>

					<!-- 包间描述 -->
					<el-form-item label="包间描述" prop="description">
						<el-input v-model="form.description" type="textarea" :rows="5" resize="vertical" />
					</el-form-item>

					<!-- 基础信息 -->
					<div class="basic-info-grid">
						<!-- 包间类型 -->
						<el-form-item label="包间类型" prop="roomType">
							<el-select v-model="form.roomType" placeholder="请选择包间类型">
								<el-option v-for="item in roomTypeOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>

						<!-- 容纳人数 -->
						<el-form-item label="容纳人数" prop="seatingCapacity">
							<el-input-number v-model="form.seatingCapacity" :min="1" :max="100" />
						</el-form-item>

						<!-- 包间费用 -->
						<el-form-item label="包间费用(元)" prop="fee">
							<el-input-number v-model="form.fee" :precision="2" :step="0.01" :min="0" />
						</el-form-item>

						<!-- 包间状态 -->
						<el-form-item label="包间状态" prop="status">
							<el-select v-model="form.status" placeholder="请选择包间状态">
								<el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</div>

					<!-- 不可预约日期 -->
					<el-form-item label="不可预约时间">
						<div class="unavailable-dates-container">
							<el-date-picker v-model="newUnavailableDate" type="datetime" placeholder="选择不可预约时间"
								value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate"
								:default-time="defaultTime" />
							<el-button type="primary" @click="addUnavailableDate" :disabled="!newUnavailableDate">
								添加
							</el-button>

							<div class="dates-list">
								<el-tag v-for="(date, index) in form.unavailableDates" :key="index" closable
									@close="removeUnavailableDate(date,index)">
									{{ formatDateTime(date.unavailableDate) }}
								</el-tag>
							</div>
						</div>
					</el-form-item>
				</el-form>
			</div>

			<!-- 右侧预览区域 -->
			<div class="preview-container">
				<h2 class="section-title">包间预览</h2>

				<!-- 封面图片 -->
				<div class="preview-image">
					<template v-if="form.image">
						<img :src="form.image" />
					</template>
					<template v-else-if="form.roomImages && form.roomImages.length > 0">
						<img :src="form.roomImages[0].imageUrl" />
					</template>
					<div v-else class="no-image">暂无封面图片</div>
				</div>

				<!-- 包间信息 -->
				<div class="preview-details">
					<h3>{{ form.roomName || "未设置包间名称" }}</h3>

					<ul>
						<li><el-icon>
								<User />
							</el-icon> 容纳人数: {{ form.seatingCapacity || "未设置" }}人</li>
						<li><el-icon>
								<Coin />
							</el-icon> 费用: {{ form.fee ? `¥${form.fee}` : "免费" }}</li>
						<li><el-icon>
								<OfficeBuilding />
							</el-icon> 类型: {{ getRoomTypeText(form.roomType) }}</li>
						<li><el-icon>
								<CircleCheck />
							</el-icon> 状态: {{ getStatusText(form.status) }}</li>
					</ul>

					<div class="description">
						<h4>包间描述</h4>
						<p>{{ form.description || "暂无包间描述" }}</p>
					</div>

					<div class="unavailable-dates-preview"
						v-if="form.unavailableDates && form.unavailableDates.length > 0">
						<h4>不可预约日期</h4>
						<ul>
							<li v-for="(date, index) in form.unavailableDates" :key="index">
								{{ formatDateTime(date.unavailableDate) }}
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button @click="handleSaveDraft">保存草稿</el-button>
				<el-button type="primary" @click="handleSubmit">{{mode === 'edit' ? '修改包间' : '创建包间'}}</el-button>
			</div>
		</div>

		<!-- 图片预览对话框 -->
		<el-dialog v-model="previewVisible" title="图片预览" width="1000px">
			<img :src="previewImage" class="preview-dialog-img" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="downloadImage(previewImage)">下载原图</el-button>
					<el-button type="primary" @click="previewVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: 'RoomEditView',
	};
</script>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		Plus,
		User,
		Coin,
		OfficeBuilding,
		CircleCheck
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		getRoomDetail,
		uploadRoomsImages,
		insertRooms,
		updateRooms,
		deleteImage,
		saveUnavailableDate,
		deleteUnavailableDate
	} from '@/api/room.js'

	const router = useRouter()
	const route = useRoute()
	const mode = route.params.mode // 'edit' 或 'add'
	const id = route.params.id // 编辑时有值，新增时为undefined
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const form = ref({
		roomName: "",
		description: "",
		image: "",
		roomType: 1,
		seatingCapacity: 10,
		fee: 0,
		status: 0,
		roomImages: [],
		unavailableDates: []
	});

	/**
	 * 主图上传相关
	 */
	const mainImageFile = ref(null)
	const formRef = ref(null)
	const newUnavailableDate = ref('')

	/**
	 * 选项配置
	 */
	const roomTypeOptions = [{
			value: 1,
			label: "普通包间"
		},
		{
			value: 2,
			label: "豪华包间"
		},
		{
			value: 3,
			label: "VIP包间"
		}
	];

	/**
	 * 状态文本
	 */
	const statusOptions = [{
			value: 0,
			label: "不可用"
		},
		{
			value: 1,
			label: "可用"
		},
		{
			value: 2,
			label: "维护中"
		}
	];

	// 图片上传相关
	const uploadedFiles = ref([])
	const tempFiles = ref([])
	const previewVisible = ref(false)
	const previewImage = ref("")

	/**
	 * 默认时间
	 */
	const defaultTime = ref(new Date(2000, 1, 1, 0, 0, 0)); // 默认设置为00:00:00

	/**
	 * 修改日期格式化函数
	 */
	const formatDateTime = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return date.toLocaleString();
	};

	/**
	 * 表单校验规则
	 */
	const rules = {
		roomName: [{
				required: true,
				message: '请输入包间名称',
				trigger: 'blur'
			},
			{
				max: 50,
				message: '包间名称不能超过50个字符',
				trigger: 'blur'
			}
		],
		description: [{
			max: 500,
			message: '包间描述不能超过500个字符',
			trigger: 'blur'
		}],
		seatingCapacity: [{
				required: true,
				message: '请输入容纳人数',
				trigger: 'blur'
			},
			{
				type: 'number',
				min: 1,
				message: '容纳人数至少为1人',
				trigger: 'blur'
			}
		],
		fee: [{
			type: 'number',
			min: 0,
			message: '费用不能为负数',
			trigger: 'blur'
		}],
		roomType: [{
			required: true,
			message: '请选择包间类型',
			trigger: 'change'
		}],
		status: [{
			required: true,
			message: '请选择包间状态',
			trigger: 'change'
		}]
	};

	/**
	 * 获取包间类型文本
	 */
	const getRoomTypeText = (type) => {
		const option = roomTypeOptions.find(item => item.value === type);
		return option ? option.label : "未知类型";
	};

	/**
	 * 获取状态文本
	 */
	const getStatusText = (status) => {
		const option = statusOptions.find(item => item.value === status);
		return option ? option.label : "未知状态";
	};

	/**
	 * 格式化日期显示
	 */
	const formatDate = (dateString) => {
		if (!dateString) return '';
		const date = new Date(dateString);
		return date.toLocaleDateString();
	};

	/**
	 * 处理主图文件变化
	 */
	const handleMainImageChange = (file) => {
		mainImageFile.value = file.raw
		// 本地预览
		const reader = new FileReader()
		reader.onload = (e) => {
			form.value.image = e.target.result
		}
		reader.readAsDataURL(file.raw)
	}

	/**
	 * 上传主图
	 */
	const uploadMainImage = async () => {
		if (!mainImageFile.value) return

		try {
			const formData = new FormData()
			formData.append('images', mainImageFile.value);
			const res = await uploadRoomsImages(formData)
			if (res.code === 200 && res.data.length > 0) {
				form.value.image = res.data[0].imageUrl
				ElMessage.success('主图上传成功')
				return true
			} else {
				ElMessage.error(res.message || '主图上传失败')
				return false
			}
		} catch (error) {
			console.error('主图上传失败:', error)
			ElMessage.error('主图上传失败')
			return false
		}
	}

	/**
	 * 显示图片预览
	 */
	const showPreview = (file) => {
		previewImage.value = file.url;
		previewVisible.value = true;
	};

	/**
	 * 下载图片
	 */
	const downloadImage = (url) => {
		const link = document.createElement("a");
		link.href = url;
		link.download = `room-image-${new Date().getTime()}.jpg`;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	};

	/**
	 * 删除图片
	 */
	const handleRemoveImage = (file, fileList) => {
		return new Promise((resolve, reject) => {
			ElMessageBox.confirm("确定删除该图片吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				if (file.id) {
					// 已上传文件：调用 API 删除
					deleteImage(file.id)
						.then(() => {
							// 从 form.roomImages 中移除
							form.value.roomImages = form.value.roomImages.filter(img => img.id !==
								file.id);
							ElMessage.success("删除成功");
							resolve(true);
						})
						.catch((error) => {
							ElMessage.error("删除失败：" + error.message);
							reject(false);
						});
				} else {
					// 本地未上传文件：仅从 tempFiles 中移除
					tempFiles.value = tempFiles.value.filter(f => f.uid !== file.uid);
					ElMessage.success("删除成功");
					resolve(true);
				}
			}).catch(() => {
				reject(false); // 用户取消删除
			});
		});
	};

	/**
	 * 存储没上传的图片
	 */
	const handleFileChange = (file, fileList) => {
		// 过滤出未上传的文件（status 为 'ready' 的文件）
		const pendingFiles = fileList.filter(item => item.status === 'ready');
		// 确保不超过限制
		tempFiles.value = pendingFiles.slice(-5);
	}

	/**
	 * 自定义图片上传方法
	 */
	const customUpload = async () => {
		try {
			// 调用API上传
			const files = tempFiles.value.map(item => item.raw || item);

			if (files.length === 0) {
				console.error('没有有效的文件可上传');
				return;
			}

			const formData = new FormData();
			files.forEach(file => {
				formData.append('images', file);
			});

			const response = await uploadRoomsImages(formData);

			// 上传成功处理
			if (response.code === 200) {
				ElMessage.success('图片上传成功')
				const roomImages = form.value.roomImages.map(img => ({
					imageUrl: img.imageUrl,
					id: img.id
				}));
				roomImages.push(...response.data)
				uploadedFiles.value = roomImages
			} else {
				ElMessage.error(response.message || '图片上传失败')
				return Promise.reject(new Error('图片上传失败'))
			}
		} catch (error) {
			console.error('图片上传出错:', error)
			ElMessage.error('图片上传出错')
			return Promise.reject(error)
		}
	}

	/**
	 * 手动触发上传所有文件
	 */
	const submitUpload = async () => {
		try {
			// 如果有新上传的主图，先上传主图
			if (mainImageFile.value) {
				const uploadSuccess = await uploadMainImage()
				if (!uploadSuccess) return
			}

			await customUpload()
			return true
		} catch (error) {
			console.error('批量上传失败', error)
			return false
		}
	}

	/**
	 * 修改添加不可预约时间的函数
	 */
	const addUnavailableDate = () => {
		if (!newUnavailableDate.value) return;

		// 检查是否已存在
		const exists = form.value.unavailableDates.some(
			date => new Date(date.unavailableDate).getTime() === new Date(newUnavailableDate.value).getTime()
		);

		if (exists) {
			ElMessage.warning('该时间已设置为不可预约');
			return;
		}

		form.value.unavailableDates.push({
			id: Date.now().toString(), // 临时ID
			unavailableDate: newUnavailableDate.value
		});

		newUnavailableDate.value = '';
		ElMessage.success('已添加不可预约时间');
	};

	/**
	 * 创建包间/修改包间
	 */
	const handleSubmit = async () => {
		try {
			await formRef.value.validate();

			// 创建要提交的数据对象，排除unavailableDates
			const submitData = {
				...form.value,
				roomImages: form.value.roomImages.map(img => ({
					imageUrl: img.imageUrl,
					roomId: img.roomId || id
				}))
			};
			delete submitData.unavailableDates; // 移除不可预约时间字段

			// 调用创建或更新API
			const apiCall = mode === 'edit' ? updateRooms : insertRooms;
			const res = await apiCall(submitData);

			if (res.code === 200 || res.code === 204) {
				ElMessage.success(res.message || '操作成功');
				if (mode === 'add') {
					router.push({
						name: 'RoomList'
					});
				} else {
					// 编辑模式，重新加载数据
					fetchRoomData();
				}
			} else {
				ElMessage.error(res.message || '操作失败');
			}
		} catch (error) {
			console.error('提交失败:', error);
			ElMessage.error(`操作失败: ${error.message || '请检查表单数据'}`);
		}
	};


	/**
	 * 保存草稿
	 */
	const handleSaveDraft = () => {
		ElMessage.success("草稿保存成功");
	};

	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back();
			})
			.catch(() => {});
	};

	/**
	 * 移除不可预约日期
	 */
	const removeUnavailableDate = async (date, index) => {
		if (mode === 'edit' && id) {
			form.value.unavailableDates.splice(index, 1);
			// await deleteUnavailableDate(date.id)
			console.log("date", date.id);
			console.log("index", index);
			ElMessage.success('已移除不可预约日期');
		} else {
			form.value.unavailableDates.splice(index, 1);
			console.log("date", date);
			console.log("index", index);
			ElMessage.success('已移除不可预约日期');
		}
	};

	/**
	 * 禁用今天之前的日期
	 */
	const disabledDate = (time) => {
		return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
	};

	/**
	 * 获取包间详情
	 */
	const fetchRoomData = async () => {
		loading.value = true;
		try {
			const res = await getRoomDetail(id);
			if (res.data) {
				form.value = res.data;
			}
		} catch (error) {
			ElMessage.error('获取包间详情失败');
		} finally {
			loading.value = false;
		}
	};

	onMounted(() => {
		if (mode === 'edit' && id) {
			fetchRoomData();
		}
	});
</script>

<style scoped>
	.room-manage-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 2;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.preview-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 20px;
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.preview-image {
		width: 100%;
		height: 12rem;
		overflow: hidden;
		border-radius: 4px;
		margin-bottom: 1.5rem;
	}

	.preview-image img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.no-image {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f3f4f6;
		color: #9ca3af;
	}

	.preview-details h3 {
		font-size: 1.1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.preview-details ul {
		list-style: none;
		padding: 0;
		margin-bottom: 1.5rem;
	}

	.preview-details li {
		margin-bottom: 0.75rem;
		color: #6b7280;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.preview-details h4 {
		font-size: 0.875rem;
		font-weight: 500;
		color: #4b5563;
		margin-bottom: 0.5rem;
	}

	.description p {
		color: #6b7280;
		font-size: 0.875rem;
		line-height: 1.5;
	}

	.basic-info-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 1.5rem;
	}

	.preview-dialog-img {
		width: 100%;
		max-height: 500px;
		object-fit: contain;
	}

	.dialog-footer {
		text-align: right;
	}

	.upload-footer {
		margin-top: 10px;
		text-align: center;
	}

	.avatar-uploader {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 178px;
		height: 100px;
	}

	.avatar-uploader:hover {
		border-color: var(--el-color-primary);
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 100px;
		text-align: center;
		line-height: 100px;
	}

	.avatar {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.unavailable-dates-container {
		width: 100%;
	}

	.unavailable-dates-container .el-date-picker {
		margin-right: 10px;
	}

	.dates-list {
		margin-top: 15px;
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
	}

	.unavailable-dates-preview {
		margin-top: 15px;
	}

	.unavailable-dates-preview ul {
		list-style: none;
		padding: 0;
		margin-top: 8px;
	}

	.unavailable-dates-preview li {
		color: #f56c6c;
		font-size: 0.875rem;
		margin-bottom: 5px;
	}
</style>